import os
import sys

# 添加项目根目录到 Python 路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
from git import Repo
from configuration import Config
from analyzer import GitChangeHandler

app = FastAPI()
config = Config()

class CommitRequest(BaseModel):
    repo_path: str
    commit_message: Optional[str] = None
    auto_generate: bool = True

@app.post("/api/commit")
async def generate_commit(request: CommitRequest):
    try:
        handler = GitChangeHandler(request.repo_path, config)
        if request.auto_generate:
            commit_message = handler.generate_commit_message()
        else:
            commit_message = request.commit_message
            
        if not commit_message:
            raise HTTPException(status_code=400, detail="无法生成提交信息")
            
        return {"message": commit_message}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/api/analyze/{repo_path}")
async def analyze_repo(repo_path: str):
    try:
        handler = GitChangeHandler(repo_path, config)
        diff = handler.get_git_diff()
        return {"diff": diff}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))